#include "database.h"

int database(char *buf, char *username)  
{  
	sqlite3		*db;
	int 		 ret;  
	char 		 sql[1024]={0};

	//打开指定的数据库文件,如果不存在将创建一个同名的数据库文件  
	ret = sqlite3_open("database_recv.db", &db);  
	if(ret)  
	{  
		PARSE_LOG_ERROR("Open ERROR! ERRMSG:%s\n", sqlite3_errmsg(db));  
		sqlite3_close(db);  
		return -1; 
	}
	else 
	{
		PARSE_LOG_DEBUG("Open database success!\n");  
	}

	//create table
	sprintf(sql,"create table if not exists '%s'(ID integer primary key autoincrement, DATA varchar(50));", username);
	ret=sqlite3_exec(db,sql,NULL,NULL,NULL);
	if(ret!=SQLITE_OK)
	{
		PARSE_LOG_ERROR("sqlite3_exec_create_table: %s\n", sqlite3_errmsg(db));
		return -2;
	}
	else
	{
		PARSE_LOG_DEBUG("Create table [%s] success!\n", username);  
	}

	//clean the sql
	memset(sql, 0, sizeof(sql));
	sprintf(sql, "insert into '%s' values(NULL,'%s');", username, buf);

	//exert the sqlite3_exec
	ret=sqlite3_exec(db,sql,NULL,NULL,NULL);
	if(ret!=SQLITE_OK)
	{
		PARSE_LOG_ERROR("sqlite3_exec_insert_table: %s\n",sqlite3_errmsg(db));
		return -3;		
	}

	//关闭数据库
	ret=sqlite3_close(db);
	if(ret!=SQLITE_OK)
	{
		PARSE_LOG_ERROR("sqlite3_exec_close_database: %s\n",sqlite3_errmsg(db));
	}

	return 0;  
}  

